package com.icode.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.icode.common.constant.ProductConstant;
import com.icode.common.to.SkuHasStockVo;
import com.icode.common.to.SkuReductionTo;
import com.icode.common.to.SpuBoundsTo;
import com.icode.common.to.es.SkuEsModel;
import com.icode.common.utils.R;
import com.icode.gulimall.product.entity.*;
import com.icode.gulimall.product.feign.CouponFeignService;
import com.icode.gulimall.product.feign.SearchFeignService;
import com.icode.gulimall.product.feign.WareFeignService;
import com.icode.gulimall.product.service.*;
import com.icode.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.icode.common.utils.PageUtils;
import com.icode.common.utils.Query;

import com.icode.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    AttrService attrService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService SearchFeignService;

    @Autowired
    SpuInfoDao spuInfoDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * TODO 事务回滚有待完善
     *
     * @param vo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1、保存spk基本信息 pms_spu_info
        SpuInfoEntity spuInfo = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfo);
        spuInfo.setCreateTime(new Date());
        spuInfo.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfo);
        log.debug("保存spk基本信息 pms_spu_info");
        //2、保存spu的描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity infoDesc = new SpuInfoDescEntity();
        //spuId
        Long spuId = spuInfo.getId();
        infoDesc.setSpuId(spuId);
        infoDesc.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(infoDesc);
        log.debug("保存spu的描述图片 pms_spu_info_desc");
        //3、保存spu图片集 pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuId, images);
        log.debug("保存spu图片集 pms_spu_images");

        //4、保存spu的规格参数 pms_spu_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        productAttrValueService.saveBaseAttrs(spuId, baseAttrs);
        log.debug("保存spu的规格参数 pms_spu_attr_value");

        //5、保存spu的积分信息 gulimall_sms ->sms_spu_brands
        Bounds bounds = vo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuId);
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }

        //5、保存sku的所有数据
        // 5.1)、sku的基本信息 pms_sku_info
        List<Skus> skus = vo.getSkus();
        if (!CollectionUtils.isEmpty(skus)) {
            skus.forEach(item -> {
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfo = new SkuInfoEntity();
//                private String skuName;
//                private BigDecimal price;
//                private String skuTitle;
//                private String skuSubtitle;复制了以上4个属性
                BeanUtils.copyProperties(item, skuInfo);
                skuInfo.setBrandId(spuInfo.getBrandId());
                skuInfo.setCatalogId(spuInfo.getCatalogId());
                skuInfo.setSkuDefaultImg(defaultImg);
                skuInfo.setSaleCount(0L);
                skuInfo.setSpuId(spuId);
                skuInfoService.saveSkuInfo(skuInfo);
                log.debug("sku的基本信息 pms_sku_info");

                // 5.2)、sku图片 pms_sku_images
                //TODO 没有照片：路径无需保存
                Long skuId = skuInfo.getSkuId();
                List<SkuImagesEntity> imagesEntities = item.getImages()
                        .stream()
                        .filter(img ->
                                //true：需要；    false：剔除
                                !StringUtils.isEmpty(img.getImgUrl())
                        )
                        .map(img -> {
                            SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                            skuImagesEntity.setSkuId(skuId);
                            skuImagesEntity.setDefaultImg(img.getDefaultImg());
                            skuImagesEntity.setImgUrl(img.getImgUrl());
                            return skuImagesEntity;
                        }).collect(Collectors.toList());

                skuImagesService.saveImages(imagesEntities);
                log.debug("sku图片 pms_sku_images");
                // 5.3)、sku的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> collect = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValue = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValue);
                    skuSaleAttrValue.setSkuId(skuId);
                    return skuSaleAttrValue;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(collect);
                log.debug("sku的销售属性信息 pms_sku_sale_attr_value");
                //5.4)、sku的优惠、满减等信息 gulimall_sms ->
                //                  sms_sku_ladder
                //                  sms_sku_full_reduction
                SkuReductionTo reductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, reductionTo);
                reductionTo.setSkuId(skuId);
                if (reductionTo.getFullCount() > 0 || reductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    couponFeignService.saveSpuReduction(reductionTo);
                    if (r.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfo) {
        this.baseMapper.insert(spuInfo);
    }

    @Override
    public PageUtils querySpuInfoPage(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(wapper ->
                    wapper.eq("id", key).or().like("spu_name", key)
            );
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.and(wapper ->
                    wapper.eq("publish_status", status)
            );
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            queryWrapper.and(wapper ->
                    wapper.eq("brand_id", brandId)
            );
        }
        String catalogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catalogId) && !"0".equalsIgnoreCase(catalogId)) {
            queryWrapper.and(wapper ->
                    wapper.eq("catalog_id", catalogId)
            );
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 商品上架
     *
     * @param spuId
     */
    @Override
    public void up(Long spuId) {

        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkuBySpuId(spuId);
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //  4.查询当前sku所有可以被检索的商品属性
        List<ProductAttrValueEntity> attrBySpuId = productAttrValueService.getAttrBySpuId(spuId);
        List<Long> attrIds = attrBySpuId.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //可检索的属性并转换为Set
        List<Long> attrSearch = attrService.selectSearchAttrIds(attrIds);
        Set<Long> idSet = new HashSet<>(attrSearch);

        List<SkuEsModel.Attrs> attrsList = attrBySpuId.stream().filter(item -> idSet.contains(item.getAttrId()))
                .map(item -> {
                    SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
                    BeanUtils.copyProperties(item, attrs);
                    return attrs;
                }).collect(Collectors.toList());

        Map<Long, Boolean> stockMap = null;

        //  1.发送远程调用，库存系统查询是否有库存
        try {
            R result = wareFeignService.checkHasStockBySkuId(skuIds);

            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
            stockMap = result.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));

        } catch (Exception e) {
            log.error("库存服务查询异常：原因{}", e);
        }

        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> skuEsModels = skuInfoEntities.stream().map(item -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(item, skuEsModel);
            //skuStock、skuImg
            skuEsModel.setSkuPrice(item.getPrice());
            skuEsModel.setSkuImg(item.getSkuDefaultImg());

            //设置库存信息
            if (finalStockMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalStockMap.get(item.getSkuId()));
            }

            // TODO 2.热度评分，0
            skuEsModel.setHotScore(0L);
            //  3.查询品牌、分类和名字的信息
            BrandEntity byId = brandService.getById(item.getBrandId());
            skuEsModel.setBrandName(byId.getName());
            skuEsModel.setBrandImg(byId.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            skuEsModel.setAttrs(attrsList);
            return skuEsModel;
        }).collect(Collectors.toList());

        //TODO 5.将数据发送给es gulimall-search
        R r = SearchFeignService.productStatusUp(skuEsModels);
        Integer code = r.getCode();
        if (r.getCode() == 0) {
            //远程调用成功
            // TODO 6.修改当前spu的状态
            this.spuInfoDao.updateStatusById(spuId, ProductConstant.ProductStatusEnum.SPU_UP.getCode());
        } else {
            //远程调用失败
            //TODO 重复调用问题？接口幂等性：重试机制
        }

    }

    /**
     * 用skuId获取spuInfo
     * @param skuId
     * @return
     */
    @Override
    public SpuInfoEntity getInfoBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long spuId = byId.getSpuId();
        SpuInfoEntity infoEntity = this.getById(spuId);
        return infoEntity;
    }

}